package com.cskaoyan.service;

import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.domain.*;
import com.cskaoyan.bean.goods.BasePageData;
import com.cskaoyan.bean.goods.CatAndBrandVo;
import com.cskaoyan.bean.goods.GoodsAddBO;
import com.cskaoyan.bean.goods.GoodsEchoVo;
import com.cskaoyan.bean.goods.smallVo.BrandVo;
import com.cskaoyan.bean.goods.smallVo.CategoryVo;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongProject: mall35th
 * @BelongPackage: com.cskaoyan.service
 * @Author: zijin
 * @Createtime: 2021-11-30 星期二 09:16
 * @Description: todo
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsSpecicationMapper specicationMapper;

    @Autowired
    GoodsProductMapper productMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsAttributeMapper attributeMapper;

    @Autowired
    BrandMapper brandMapper;

    /**
     * 查询需要根据显示delete标记进行查询
     * @param goodsId
     * @param goodsSn
     * @param name
     * @param pageParams
     * @return
     */
    @Override
    public BasePageData queryGoodsByCondition(Integer goodsId, String goodsSn, String name, BaseParam pageParams) {
        if (pageParams.getLimit() == 0){
            /**
             * limit为0，则直接查询
             */
            GoodsExample example = new GoodsExample();
            example.createCriteria().andDeletedEqualTo(false);
            List<Goods> goods_noCondition = goodsMapper.selectByExampleWithBLOBs(example);
            return BasePageData.ok(goods_noCondition,pageParams);
        }
        PageHelper.startPage(pageParams.getPage(),pageParams.getLimit());
        /**
         * 查询商品详情
         */
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (goodsId != null){
            criteria.andIdEqualTo(goodsId);
        }
        if (goodsSn != null && !"".equals(goodsSn.trim())){
            criteria.andGoodsSnLike("%" + goodsSn + "%");
        }
        if (name != null && !"".equals(name.trim())){
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        goodsExample.setOrderByClause(pageParams.getSort() + " " + pageParams.getOrder());
        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        BasePageData goodsList = BasePageData.ok(goods,pageParams);
        return goodsList;
    }

    @Override
    public GoodsEchoVo queryDetails(Integer id) {
        GoodsEchoVo goodsEchoVo = new GoodsEchoVo();
        /**
         * 查询商品，仅有一个
         */
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(id);
        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        /**
         * 此处得到categoryId
         */
        Integer categoryId = goods.get(0).getCategoryId();
        goodsEchoVo.setGoods(goods.get(0));
        /**
         * 查询商品规格，返回的为数组
         */
        GoodsSpecicationExample specicationExample = new GoodsSpecicationExample();
        specicationExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsSpecication> specicationsList = specicationMapper.selectByExample(specicationExample);
        goodsEchoVo.setSpecifications(specicationsList);
        /**
         * 查询产品，返回数组
         */
        GoodsProductExample productExample = new GoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsProduct> products = productMapper.selectByExample(productExample);
        goodsEchoVo.setProducts(products);
        /**
         * 查询category表根据categoryId进行查询,只有一个数据
         */
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andIdEqualTo(categoryId);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        if (categories.get(0) != null){
            Integer pid = categories.get(0).getPid();
            Integer[] num = {pid,categoryId};
            goodsEchoVo.setCategoryIds(num);
        }

        /**
         *获取商品参数表数据
         */
        GoodsAttributeExample attributeExample = new GoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsAttribute> attributeList = attributeMapper.selectByExample(attributeExample);
        goodsEchoVo.setAttributes(attributeList);
        return goodsEchoVo;
    }

    @Override
    public CatAndBrandVo queryCatgoryAndBrand() {
        CatAndBrandVo catAndBrandVo = new CatAndBrandVo();
        /**
         * 首先查询品牌列表
         */
        BrandExample brandExample = new BrandExample();
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        List<BrandVo> brandList = new ArrayList<>();
        for (Brand brand : brands) {
            BrandVo brandVo = new BrandVo();
            brandVo.setValue(brand.getId());
            brandVo.setLabel(brand.getName());
            brandList.add(brandVo);
        }
        catAndBrandVo.setBrandList(brandList);

        /**
         * 查询category表，该表存在层次关系
         * 二级关系，嵌套循环   L1 L2
         */
        /**
         * 查询L1级商品类型
         */
        List<CategoryVo> categoryVoList = new ArrayList<>();
        CategoryExample categoryExample1 = new CategoryExample();
        categoryExample1.createCriteria().andPidEqualTo(0);
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample1);
        for (Category category : categoryList) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setValue(category.getId());
            categoryVo.setLabel(category.getName());
            /**
             * 内层嵌套循环，查询二级商品种类
             */
            Integer id = category.getId();
            CategoryExample categoryExample2 = new CategoryExample();
            categoryExample2.createCriteria().andPidEqualTo(id);
            List<Category> categories = categoryMapper.selectByExample(categoryExample2);
            //内层种类
            List<CategoryVo> categoryVoList1 = new ArrayList<>();
            for (Category category1 : categories) {
                CategoryVo categoryVo1 = new CategoryVo();
                categoryVo1.setValue(category1.getId());
                categoryVo1.setLabel(category1.getName());
                categoryVo1.setChildren(null);
                categoryVoList1.add(categoryVo1);
            }
            categoryVo.setChildren(categoryVoList1);
            categoryVoList.add(categoryVo);
        }
        catAndBrandVo.setCategoryList(categoryVoList);
        return catAndBrandVo;
    }


    /**
     * 需要获取商品id
     * @param goodsAddBO
     * @return
     */
    @Transactional
    @Override
    public boolean createGoods(GoodsAddBO goodsAddBO) {
        Goods goods  = goodsAddBO.getGoods();

        /**
         * 插入数据到商品表
         * 获取自增主键
         */
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goodsMapper.insertSelective(goods);
        Integer id = goods.getId();
        /**
         * 插入数据到产品表
         */
        List<GoodsProduct> products = goodsAddBO.getProducts();
        for (GoodsProduct product : products) {
            product.setGoodsId(id);
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            productMapper.insertSelective(product);
        }
        /**
         * 插入数据到商品参数表
         */
        List<GoodsAttribute> attributes = goodsAddBO.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            attribute.setGoodsId(id);
            attributeMapper.insertSelective(attribute);
        }
        List<GoodsSpecication> specifications = goodsAddBO.getSpecifications();
        for (GoodsSpecication specification : specifications) {
            specification.setAddTime(new Date());
            specification.setUpdateTime(new Date());
            specification.setGoodsId(id);
            specicationMapper.insertSelective(specification);
        }
        return true;
    }

    /**
     * 更新时候是有可能会出现重新插入的
     * @param goodsAddBO
     * @return
     */
    @Transactional
    @Override
    public boolean updateGoods(GoodsAddBO goodsAddBO) {
        Goods goods = goodsAddBO.getGoods();
        Integer goodsId = goods.getId();
        List<GoodsProduct> products = goodsAddBO.getProducts();
        List<GoodsAttribute> attributes = goodsAddBO.getAttributes();
        List<GoodsSpecication> specifications = goodsAddBO.getSpecifications();
        try{
            /**
             * 更新商品
             */
            goods.setUpdateTime(new Date());
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.createCriteria().andIdEqualTo(goods.getId());
            goodsMapper.updateByExampleWithBLOBs(goods,goodsExample);
            /**
             * 更新product表
             */
            for (GoodsProduct product : products) {
                product.setUpdateTime(new Date());
                GoodsProductExample productExample = new GoodsProductExample();
                productExample.createCriteria().andIdEqualTo(product.getId());
                productMapper.updateByExample(product,productExample);
            }
            /**
             * 1.根据商品id将所有的attribute数据的状态设置为1
             * 2.循环遍历的时候，更新后再更新attribute的值
             * 3.循环的过程中没有id的情况，则新增，添加增加时间和商品id
             */
            //1.数据标记为删除
            attributeMapper.updateAttributeStatusByGoodsId(goodsId,1);
            //2.循环遍历
            for (GoodsAttribute attribute : attributes) {
                if (attribute.getId() == null){
                    /**
                     * 3.此种情况即为新增了attribute数据
                     * 设置attribute的id和创建时间和更新时间
                     */
                    attribute.setGoodsId(goodsId);
                    attribute.setAddTime(new Date());
                    attribute.setUpdateTime(new Date());
                    attributeMapper.insertSelective(attribute);
                    continue;
                }
                /**
                 *2.更新attribute数据
                 * 注意更新delete状态和更新时间
                 */
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(false);
                GoodsAttributeExample attributeExample1 = new GoodsAttributeExample();
                attributeExample1.createCriteria().andIdEqualTo(attribute.getId());
                attributeMapper.updateByExampleSelective(attribute,attributeExample1);
            }

            /**
             * 更新specifications表
             */
            for (GoodsSpecication specification : specifications) {
                specification.setUpdateTime(new Date());
                GoodsSpecicationExample specicationExample = new GoodsSpecicationExample();
                specicationExample.createCriteria().andIdEqualTo(specification.getId());
                specicationMapper.updateByExampleSelective(specification,specicationExample);
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除商品，给对应的数据添加删除标记
     * @param goods
     * @return
     */
    @Override
    public boolean deleteGoods(Goods goods) {
        goods.setUpdateTime(new Date());
        goods.setDeleted(true);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(goods.getId());
        try{
            goodsMapper.updateByExampleSelective(goods,goodsExample);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * zhiMing 根据商品id返回商品信息
     */
    @Override
    public Goods queryDetailById(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        return goods;
    }


}
